<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { deleteDoctorPatient, getDoctorPatientList, type PatientVO } from '@/apis/doctor/doctorPatientAPI'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDoctorStore } from '@/stores/doctor' // 假设有用户store用于获取医生ID

const router = useRouter()
const doctorStore = useDoctorStore()

// 搜索条件
const patientName = ref('')
const status = ref('')
const loading = ref(false)

// 表格数据
const tableData = ref<PatientVO[]>([])

// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取患者列表数据
const getPatientList = async () => {
  loading.value = true
  try {
    const res = await getDoctorPatientList({
      doctorId: doctorStore.doctorId.toString(), // 确保传递字符串类型
      name: patientName.value || undefined,
      status: status.value || undefined,
      pageNum: currentPage.value.toString(),
      pageSize: pageSize.value.toString()
    })

    if (res.status === 200 && res.data) {
      tableData.value = res.data.records
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取患者列表失败')
    }
  } catch (error) {
    console.error('获取患者列表出错:', error)
    ElMessage.error('获取患者列表失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1 // 重置到第一页
  getPatientList()
}

// 处理重置
const handleReset = () => {
  patientName.value = ''
  status.value = ''
  currentPage.value = 1
  getPatientList()
}

// 处理分页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getPatientList()
}

// 处理每页显示条数变化
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
  getPatientList()
}

// 处理详情
const handleDetail = (row: PatientVO) => {
  router.push({
    path: `/doctor/patient-detail/${row.id}`,
    query: { ...row }
  })
}

// 处理编辑
const handleEdit = (row: PatientVO) => {
  console.log('编辑', row)
}

// 处理删除
const handleDelete = (row: PatientVO) => {
  ElMessageBox.confirm('确定要删除该患者记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteDoctorPatient({ patientIds: [row.id] })
      .then(() => {
        ElMessage.success('删除成功')
        getPatientList() // 重新加载数据
      })
      .catch(error => {
        console.error('删除患者失败:', error)
        ElMessage.error('删除患者失败，请稍后重试')
      })
  }).catch(() => {
    // 取消删除
  })
}

// 获取状态标签类型
const getStatusType = (status: string) => {
  switch (status) {
    case 'ACCEPTED':
      return 'warning' // 就诊中
    case 'COMPLETED':
      return 'success' // 已结束
    default:
      return 'info'
  }
}

// 格式化状态显示文本
const formatStatus = (status: string) => {
  switch (status) {
    case 'ACCEPTED':
      return '就诊中'
    case 'COMPLETED':
      return '已结束'
    default:
      return status
  }
}

// 页面加载时获取数据
onMounted(() => {
  getPatientList()
})
</script>

<template>
  <div class="patient-list">
    <!-- 搜索区域 -->
    <div class="search-section">
      <el-form :inline="true">
        <el-form-item label="患者姓名">
          <el-input v-model="patientName" placeholder="请输入患者姓名" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="status" placeholder="请选择状态">
            <el-option label="全部" value="" />
            <el-option label="就诊中" value="ACCEPTED" />
            <el-option label="已结束" value="COMPLETED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table :data="tableData" style="width: 100%" border v-loading="loading">
      <el-table-column prop="name" label="姓名" />
      <el-table-column prop="phone" label="电话" width="120" />
      <el-table-column prop="acceptTime" label="接诊时间" width="160" />
      <el-table-column prop="completedTime" label="完成时间" width="160" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusType(row.status)">{{ formatStatus(row.status) }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button size="small" @click="handleDetail(row)">详情</el-button>
          <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<style scoped lang="scss">
.patient-list {
  padding: 20px;

  .search-section {
    background: #f5f7fa;
    padding: 20px;
    border-radius: 12px;
    margin-bottom: 20px;
  }

  :deep(.el-table) {
    background: #f5f7fa;
    border-radius: 12px;
    overflow: hidden;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
    background: #f5f7fa;
    padding: 20px;
    border-radius: 12px;
  }
}
</style>
